package cn.zh.org.service.impl;

import cn.zh.base.service.impl.BaseServiceImpl;
import cn.zh.base.util.AjaxResult;
import cn.zh.base.util.PageList;
import cn.zh.org.domain.Department;
import cn.zh.org.mapper.DepartmentMapper;
import cn.zh.org.query.DepartmentQuery;
import cn.zh.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    @Override
    public List<Department> tree() {
        // 只收一级部门的list
        ArrayList<Department> list = new ArrayList<>();
        // 查询所有部门
        List<Department> all = findAll();
        // 结合all调用stream流生成Map集合
        Map<Long, Department> map = all.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        for (Department dept: all) {
            // 如果没有父id为一级部门
            if (dept.getParentId()==null) {
                // 放入一级部门list
                list.add(dept);
            // 剩下的是有上级部门的部门
            } else {
                // map get key 获得 value，通过上级id获得上级部门
                Department parent = map.get(dept.getParentId());
                if (null != parent){
                    // 上级部门添加当前遍历部门到List类型的children集合属性里
                    parent.getChildren().add(dept);
                }
            }
        }
        // 返回一级部门
        return list;
    }


}
